package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Component
public class TrackReceiver {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true"),
            key = {MqConst.ROUTING_TRACK_STAT_UPDATE}
    ))
    public void updateStat(String content, Message message, Channel channel) {
        if(!StringUtils.isEmpty(content)) {
            TrackStatMqVo trackStatMqVo =
                    JSON.parseObject(content, TrackStatMqVo.class);
            if(trackStatMqVo != null) {
                //1 获取发送端传递业务编号
                String businessNo = trackStatMqVo.getBusinessNo();
                //2 redis添加数据，使用setnx方法
                Boolean setIfAbsent =
                        redisTemplate.opsForValue().setIfAbsent(businessNo,
                                1, 1, TimeUnit.HOURS);
                //3 如果添加成功，证明第一次消费，
                if(setIfAbsent) {
                    //更新
                    trackInfoService.updateStat(trackStatMqVo);
                }
            }
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
